<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <comment-item @click-reply="$emit('click-reply',$event)" :comment="item" v-for="item in list" :key="item.com_id + '' " />
    </van-list>
    <!-- 评论列表 -->

    <!-- 发布评论 -->
    <van-cell-group class="publish-wrap">
      <van-field clearable placeholder="请输入评论内容">
        <van-button slot="button" size="mini" type="info">发布</van-button>
      </van-field>
    </van-cell-group>
    <!-- /发布评论 -->
  </div>
</template>

<script>
import { getArticleComments } from '@/api/article'
import commentItem from './commentItem.vue'
export default {
  components: { commentItem },
  name: 'ArticleComment',
  props: {
    // 获取评论列表的数据类型
    type: {
      type: String,
      default: 'a'
    },
    // 传递的源id 文章id或评论id
    source: {
      type: [String, Number, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      // 获取一页的标识，第一页不用传，第二页在第一页的标识基础上传
      offset: null,
      limit: 10
    }
  },
  methods: {
    async onLoad () {
      try {
        const { results, last_id: lastId, total_count: total } = await getArticleComments({
          type: this.type,
          source: this.source,
          offset: this.offset,
          limit: this.limit
        })
        this.$emit('on-success-total', total)
        this.list.push(...results)
        this.loading = false
        if (!results.length) {
          this.finished = true
        } else {
          this.offset = lastId
        }
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style scoped lang="less">
  .publish-wrap {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
  }

  .van-list {
    margin-bottom: 45px;
  }
</style>
